Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
variable updated inside ".then" in fetch not reflected outside in Javascript

I tried updating IndexedDB data inside ".then" in fetch but that doesn't work inside event handlers as I got to know that from this post post-link. Updating the IndexedDB data outside the ".then" is working. So I created a boolean variable and tried updating it inside the ".then" and thought of updating the IndexedDB data outside but the boolean value is not getting updated inside the ".then".

.then(() =>{
        data_inserted = true ;
      })

Now outside the ".then"

console.log(data_inserted); // value is false
      if ( data_inserted === true )
      {
// update IndexedDB code
      }

I saw this post post-link and I'm not sure how to do a callback function as they did for my code.

Kindly help me in updating the boolean variable.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I suspect this is a lack of understanding of async code.

The async code, then, will happen AFTER the code that follows it. Note:

let foo = "bar"
someFunctionThatTakesOneSecond()
    .then((res) => {
        foo = "baz"
        console.log("then: ", foo); 
    })
console.log("there: ", foo)

Will output:

 there: bar
 then: baz

Why? Because the code in the 'then' won't run until after `someFunctionThatTakesOneSecond" completes and the promise is fulfilled. But the code after the async block will run synchronously (ie: right away).

You may wish to use the async/await pattern instead - await stops further execution until the async function returns.

So:

let foo = "bar"
await someFunctionThatTakesOneSecond()
foo = "baz"
console.log("then: ", foo); 
console.log("there: ", foo)

Would output:

 then: baz
 there: baz

Read more on async/await and asynchronous JavaScript here: https://blog.logrocket.com/understanding-asynchronous-javascript/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda